import select
import time
from selenium import webdriver
from selenium.common import WebDriverException, NoSuchElementException, InvalidArgumentException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
from selenium.webdriver.support.wait import WebDriverWait
from common.functions import open_browser
from selenium.webdriver.support import expected_conditions as EC


class Base:
    # 初始化打开浏览器
    def __init__(self, browser):
        self.driver = browser

    # 进入网页
    def get(self, url):
        try:
            self.driver.get(url)
        except (InvalidArgumentException, WebDriverException):
            print('网址错误')

    # 浏览器后退
    def back(self):
        self.driver.back()

    # 浏览器前进
    def forward(self):
        self.driver.forward()

    # 浏览器刷新
    def refresh(self):
        self.driver.refresh()

    # 定位元素
    def find_element(self, locator, timeout=5):
        try:
            return WebDriverWait(self.driver, timeout).until(EC.presence_of_element_located(locator))
        except TimeoutError:
            print('元素定位失败')

    # 元素点击
    def click(self, locator):
        element = self.find_element(locator)
        if element is not None:
            element.click()
        else:
            print('元素没找到')

    # 元素输入
    def send_keys(self, locator, text):
        self.find_element(locator).send_keys(text)

    # 输入内容清空
    def clear(self, locator):
        self.find_element(locator).clear()

    # 获取元素属性
    def get_attribute(self, locator, attribute):
        element = self.find_element(locator)
        if element:
            return element.get_attribute(attribute)

    # 获取元素文本内容
    def get_text(self, locator):
        element = self.find_element(locator)
        if element:
            return element.text

    # 下拉框选择
    def select_index(self, locator, index):
        element = self.find_element(locator)
        if element:
            select1 = Select(element)
            select1.select_by_index(index)

    def select_value(self, locator, value):
        element = self.find_element(locator)
        if element:
            select1 = Select(element)
            select1.select_by_index(value)

    def select_text(self, locator, text):
        element = self.find_element(locator)
        if element:
            select1 = Select(element)
            select1.select_by_index(text)

    # 退出浏览器
    def quit(self, seconds=3):
        time.sleep(seconds)
        self.driver.quit()


if __name__ == '__main__':
    browser = open_browser()
    base = Base(browser)
    base.get('https://www.baidu.com')
    locator1 = (By.LINK_TEXT, '新闻')
    base.find_element(locator1)
    print(base.get_attribute(locator1, 'outerHTML'))
    print(base.get_text(locator1))
    base.quit()
